/**
 * UltraCSA平台系统文件
 * 
 * Copyright 2016 北京神州泰岳软件股份有限公司
 */
package com.ultrapower.ultracsa.product.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ultrapower.ultracsa.product.module.TaskOperator;

/**
 * 作者: xtxb
 * 
 * 日期: 2016
 * 
 * 版权说明：北京神州泰岳软件股份有限公司
 * 
 * 对Apach http client的封装，方便本地调用
 */
public class HttpClientUtil {
	private static Logger log=Logger.getLogger(HttpClientUtil.class);
	
	public static boolean curlPost(String url,Map<String,String> params){
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpost = new HttpPost(url);
		if(params!=null){
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			for (Iterator iterator = params.keySet().iterator(); iterator.hasNext();) {
				String key = (String) iterator.next();
				formparams.add(new BasicNameValuePair(key, params.get(key)));
			}
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
			httpost.setEntity(entity);
		}
		
		CloseableHttpResponse response=null;
		try {
			response=httpclient.execute(httpost);
			if(response.getStatusLine().getStatusCode()!=HttpStatus.OK.value()){
				ObjectMapper objectMapper = new ObjectMapper();
				JsonNode node = objectMapper.readTree(response.getEntity().getContent());
				log.error("处理RESTFull接口调用失败！！"+node.get("errorMsg"));
			}else{
				return true;
			}
		}catch (Exception e) {
			log.error("服务器请求失败！",e);
		}finally{
			if(response!=null)
				try {
					response.close();
				} catch (IOException e) {
					log.error("",e);
				}
		}
		return false;
	}
}
